from functools import wraps
from flask import session, request
from common.exceptions import AuthorizationFailed, IdentificationFailed, CsrfException
from util.db import Cursor


# 登录状态下的鉴权
def auth_validate(operation, resource, user_id, resource_id=None):
    # 已登录，鉴权失败
    if not authrization(operation,  resource, user_id, resource_id):
        raise AuthorizationFailed()


def authrization(operation, resource, user_id, resource_id):
    edit_flag = False
    # 如果是创建资源，查看角色是admin或editor，则可以直接创建
    roles = list(map(int, session.get('role').split(',')))
    if 1 in roles or 3 in roles:
        edit_flag = True
    if operation == 'create':
        return edit_flag
    if operation == 'edit' and not edit_flag:
        return edit_flag
    if resource_id:
        # 如果是操作已有资源，查询权限表
        with Cursor() as cursor:
            sql = f"""select `{operation}` from yugong_auth_{resource} where resource_id=%s and user_id=%s"""
            cursor.execute(sql, [resource_id, user_id])
            res = cursor.fetchall()
        if not res:
            return False
        if not res[0][operation]:
            return False
    return True
